package com.xtkj.superclub_information.config;

import com.xtkj.superclub_entity.entity.travel.Travel;
import com.xtkj.superclub_information.dao.TravelDao;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author lizheqi
 * @create 2020-01-08-14:03
 */
@Slf4j
public class Schedule extends QuartzJobBean {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TravelDao travelDao;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "0 0/30 * * * *")//每天凌晨执行
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("LikeTask-------- {}", sdf.format(new Date()));
        //将 Redis 里的阅读信息同步到数据库里
        HashOperations ops = redisTemplate.opsForHash();
        Map reads = ops.entries("read");
        Set set = reads.keySet();
        //获取所有的map即游记编号与用户阅读数
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            String travelId = iterator.next().toString();//获取游记编号
            int readNum= Integer.valueOf(reads.get(travelId).toString());//获取该篇游记的阅读数
            Travel travel = new Travel();
            travel.setReadNum(readNum).setTravelId(travelId);
            //更新数据库
            travelDao.updateById(travel);
        }
    }

}

